package cn.itcast.util;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;

public class JDBCUtil {
private static String url = null;
private static String driver = null;
static{
    //1. 注册驱动
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    //2. 加载配置文件
    Properties pro = new Properties();
    URL rs = JDBCUtil.class.getClassLoader().getResource("jdbc.properties");
    String path = rs.getPath();
    try {
        pro.load(new FileReader(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
    url = pro.getProperty("url");
    driver = pro.getProperty("driver");
    try {
        Class.forName(driver);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

}
    /**
     * 获取连接
     * @return
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url);
    }

    /**
     * 释放连接
     */
    public static void close(Connection conn,Statement stmt) throws SQLException {
        if(conn != null) conn.close();
        if(stmt != null) stmt.close();
    }
}
